package com.websocket.event;

import org.springframework.context.ApplicationEventPublisher;

import java.security.Principal;

public class EventPublisher {
    private final EventListenerConfig config;
    private final ApplicationEventPublisher publisher;

    public EventPublisher(EventListenerConfig config, ApplicationEventPublisher publisher) {
        this.config = config;
        this.publisher = publisher;
    }

    public void publishConnectEvent(Object source, Principal user) {
        if (!config.isEnable() || !config.isConnect()) return;
        publisher.publishEvent(new WebSocketConnectEvent(source, user));
    }

    public void publishDisconnectEvent(Object source, Principal user, int code) {
        if (!config.isEnable() || !config.isDisconnect()) return;
        publisher.publishEvent(new WebSocketDisconnectEvent(source, user, code));
    }

    public void publishReceiveEvent(Object source, Principal user, String message) {
        if (!config.isEnable() || !config.isReceive()) return;
        publisher.publishEvent(new WebSocketReceiveEvent(source, user, message));
    }

    public void publishPublishEvent(Object source, Principal user, String message, boolean broadcast) {
        if (!config.isEnable() || !config.isPublish()) return;
        publisher.publishEvent(new WebSocketPublishEvent(source, message, broadcast, user));
    }
}
